package qiniu

import (
	"context"
	"encoding/base64"
	"fmt"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"mime/multipart"
	"niu-video/config"
	"niu-video/pkg/logger"
	"os"
)

func newConfig() storage.Config {
	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Region = &storage.ZoneHuadong
	// 是否使用https域名
	cfg.UseHTTPS = true
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false
	return cfg
}
func UploadMp4(f multipart.File, fileSize int64, fileSha256 string) (string, error) {
	bucket := config.Conf.Qiniu.Bucket
	putPolicy := storage.PutPolicy{
		Scope:   bucket,
		SaveKey: "store/$(year)$(mon)$(day)$(hour)$(min)/" + fileSha256 + ".mp4",
		PersistentOps: fmt.Sprintf("vframe/png/offset/1/h/480|saveas/%s",
			storage.EncodedEntry(bucket, "store/$(year)$(mon)$(day)$(hour)$(min)/"+fileSha256+".mp4_cover.jpg")),
	}
	mac := qbox.NewMac(config.Conf.Qiniu.AK, config.Conf.Qiniu.SK)
	upToken := putPolicy.UploadToken(mac)

	cfg := newConfig()
	// 构建表单上传的对象
	resumeUploader := storage.NewResumeUploaderV2(&cfg)
	ret := storage.PutRet{}

	recorder, err := storage.NewFileRecorder(os.TempDir())
	if err != nil {
		logger.LogInfoIf(err)
		return "", err
	}
	// 可选配置
	putExtra := storage.RputV2Extra{
		Recorder: recorder,
		MimeType: "mp4",
	}
	err = resumeUploader.PutWithoutKey(context.Background(), &ret, upToken, f, fileSize, &putExtra)
	if err != nil {
		logger.LogInfoIf(err)
		return "", err
	}

	return config.Conf.Qiniu.Url + ret.Key, nil
}
func GetUploadToken(ticket string) string {
	bucket := config.Conf.Qiniu.Bucket
	putPolicy := storage.PutPolicy{
		Scope:      bucket,
		ReturnBody: `{"key":"$(key)","hash":"$(etag)","bucket":"$(bucket)","fsize":$(fsize),"name":"$(x:name)"}`,
		// Set persistentOps
		PersistentOps: getFopVSampleCommand(ticket, 3),
	}

	mac := qbox.NewMac(config.Conf.Qiniu.AK, config.Conf.Qiniu.SK)
	uploadToken := putPolicy.UploadToken(mac)
	return uploadToken
}

// 获取截图次数
func getFopVSampleCommand(key string, numFrames int) string {
	fopVsample := fmt.Sprintf("vsample/jpg/frames/%d/pattern/%s",
		numFrames,
		base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf("%s_$(count).jpg", key))),
	)
	return fopVsample
}
